import React, {useState} from 'react'
import { StyleSheet, Text, View, SafeAreaView, TouchableOpacity, FlatList } from 'react-native';
import Constants from 'expo-constants';

const Item = ({ item, onPress, style }) => (
    <TouchableOpacity onPress={onPress} style={[styles.item, style]}>
        <Text style={style.color}>{item.name}</Text>
    </TouchableOpacity>
);

export default function TypeList(props) {
    const typeList = props.typeList 
    const [id, setId] = useState(() => {
        if(typeList && typeList.length !== 0){
            return typeList[0].id
        }
        return 0
    })
    const handleTypeChange = (id) => {
        props.handleTypeChange(id)
        setId(id)
    }
    const renderItem = ({ item, index}) => {
        const RADIUS = 10
        const backgroundColor = item.id === id ? "#ffffff" : "#ebebeb"
        // check the previous one is activated
        let borderTopRightRadius = index === 0 ? 0 : RADIUS
        if(index !== 0){
            borderTopRightRadius = typeList[index-1].id === id ? RADIUS : 0
        }
        // check the next one is activated 
        let borderBottomRightRadius = index === typeList.length - 1 ? 0 : RADIUS
        if(index !== typeList.length - 1){
            borderBottomRightRadius = typeList[index + 1].id === id ? RADIUS : 0
        }
        
        return (
            <Item
                item={item}
                onPress={() => handleTypeChange(item.id)}
                style={{ backgroundColor, borderTopRightRadius, borderBottomRightRadius }}
            />
        );
    };
    return (
        <View style={styles.flatListContainer}>
            <FlatList
                style={styles.flatList}
                data={typeList}
                renderItem={renderItem}
                keyExtractor={(item) => String(item.id)}
                extraData={id} 
            />
        </View>
    )
}

const styles = StyleSheet.create({
    flatListContainer: {
        backgroundColor: '#ebebeb',
        width: 80
    },
    flatList: {
        backgroundColor: '#fff',
        flexGrow: 0,
    },
    item: {
        width: 80,
        paddingTop: 15,
        paddingBottom: 15,
        paddingLeft: 10
    },
    title: {
        textAlign: 'left',
        color: '#939393'
    },
    titleActive: {
    }
})